package com.hmkj.core.api.juhe.bean.epay.endpoints;

import com.alibaba.fastjson.JSON;
import com.hmkj.common.utils.StringUtils;
import com.hmkj.core.api.juhe.bean.epay.EPayConsts;
import com.hmkj.core.api.juhe.bean.epay.PayModel;
import com.hmkj.core.api.juhe.bean.epay.RealNameAuthResp;
import com.hmkj.core.api.juhe.bean.epay.WithHoldingResp;
import com.hmkj.core.api.juhe.bean.epay.base.DcEndPoint;
import com.hmkj.core.api.juhe.bean.epay.base.MD5;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Description: 双乾支付接口
 * Created by shiyaxiang on 2017/1/3 17:36.
 */
public class PaymentEndPoint extends DcEndPoint {

    private final String sslpayment = "/sslpayment";


    public PaymentEndPoint(String md5key, String merNo, String payType) {
        super(md5key, merNo, payType);
    }

    public static RealNameAuthResp sendCode(List<NameValuePair> formparams) {

        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost("https://fastpay.95epay.cn/realnameAuth.action");
        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String responseStr = EntityUtils.toString(entity, "UTF-8");
                    System.out.println("Response content: " + responseStr);
                    if (!StringUtils.isBlank(responseStr)) {
                        return JSON.parseObject(responseStr, RealNameAuthResp.class);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 快捷支付-接口版
     */
    public WithHoldingResp hfDaiKouTrade(String smsCode, String phone, String idCardNo, String idType, PayModel bank, String payAmount, String merOrderNo,
                                         String txnTime, String notifyUrl) {

        String MD5Info;                    // MD5 加密字符串
        MD5 md5 = new MD5();
        String apiUrl ="";
        //todo
        String NotifyURL = apiUrl + notifyUrl;

        String[] md5ReqMap = new String[]{"merNo", "merOrderNo", "custName", "phone", "cardNo", "idType",
                "idNo", "payAmount", "bankCode", "NotifyURL"};

        Map<String, String> mapStr = new LinkedHashMap<>();
        String[] value = new String[]{merNo, merOrderNo, bank.getAccountName(), phone, bank.getBankNo(), idType, idCardNo
                , payAmount, bank.getBankCode(), NotifyURL};
        for (int i = 0; i < md5ReqMap.length; i++) {
            mapStr.put(md5ReqMap[i], value[i]);
        }

        String strBeforeMd5 = joinMapValue(mapStr, '&') + md5.getMD5Info(md5key).toUpperCase();

        System.out.println(strBeforeMd5);

        MD5Info = md5.getMD5Info(strBeforeMd5).toUpperCase();

        System.out.println(MD5Info);

        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost("https://fastpay.95epay.cn/pay/hfDaikouTrade.action");
        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<>();

        formparams.add(new BasicNameValuePair("merNo", merNo));
        formparams.add(new BasicNameValuePair("merOrderNo", merOrderNo));
        formparams.add(new BasicNameValuePair("cardNo", bank.getBankNo()));
        formparams.add(new BasicNameValuePair("custName", bank.getAccountName()));
        formparams.add(new BasicNameValuePair("idType", idType));
        formparams.add(new BasicNameValuePair("idNo", idCardNo));
        formparams.add(new BasicNameValuePair("phone", phone));
        formparams.add(new BasicNameValuePair("purpose", phone + "快捷支付" + payAmount + "元")); //交易信息
        formparams.add(new BasicNameValuePair("payAmount", payAmount)); //交易信息
        formparams.add(new BasicNameValuePair("bankCode", bank.getBankCode()));
        formparams.add(new BasicNameValuePair("payType", "RZPAY"));//固定：RZPAY（认证支付）
        formparams.add(new BasicNameValuePair("NotifyURL", NotifyURL)); //异步通知地址
        formparams.add(new BasicNameValuePair("txnTime", txnTime));
        formparams.add(new BasicNameValuePair("smsCode", smsCode));
        formparams.add(new BasicNameValuePair("MD5Info", MD5Info));

        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String responseStr = EntityUtils.toString(entity, "UTF-8");
                    System.out.println("Response content: " + responseStr);
                    if (!StringUtils.isBlank(responseStr)) {
                        return JSON.parseObject(responseStr, WithHoldingResp.class);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String joinMapValue(Map<String, String> map, char connector) {

        StringBuilder b = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            b.append(entry.getKey());
            b.append('=');
            if (entry.getValue() != null) {
                b.append(entry.getValue());
            }
            b.append(connector);
        }
        return b.toString();
    }

    /**
     * 组装请求参数-发送短信验证码接口
     *
     * @param model
     * @param transDate
     * @param transTime
     * @param mercNo
     * @param md5key
     * @return
     */
    public static List<NameValuePair> buildRealNameParams(PayModel model, String transDate, String transTime, String mercNo, String md5key) throws Exception{

        String MD5Info;                    // MD5 加密字符串
        MD5 md5 = new MD5();
        String cardType = "D";
        String year = "";
        String month = "";
        String cvn2 = "";

        String[] md5ReqMap = new String[]{"merNo", "custName", "phone", "cardNo", "idNo", "idType",
                "payAmount", "merOrderNo", "cardType", "year", "month", "CVV2", "transDate", "transTime"};

        model.setBankCode(model.getBankCode());
        Map<String, String> mapStr = new LinkedHashMap<>();
        String[] value = new String[]{mercNo, model.getAccountName(), model.getPhone(), model.getBankNo(), model.getIdCardNo(), EPayConsts.ID_TYPE_0, model.getAmount()
                , model.getMerOrderNo(), cardType, year, month, cvn2, transDate, transTime};
        for (int i = 0; i < md5ReqMap.length; i++) {
            mapStr.put(md5ReqMap[i], value[i]);
        }

        String strBeforeMd5 = joinMapValue(mapStr, '&') + md5.getMD5Info(md5key).toUpperCase();

        System.out.println(strBeforeMd5);

        MD5Info = md5.getMD5Info(strBeforeMd5).toUpperCase();

        System.out.println(MD5Info);

        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<>();

        formparams.add(new BasicNameValuePair("merNo", mercNo));
        formparams.add(new BasicNameValuePair("merOrderNo", model.getMerOrderNo()));
        formparams.add(new BasicNameValuePair("cardNo", model.getBankNo()));
        formparams.add(new BasicNameValuePair("custName", model.getAccountName()));
        formparams.add(new BasicNameValuePair("idType", EPayConsts.ID_TYPE_0));
        formparams.add(new BasicNameValuePair("idNo", model.getIdCardNo()));
        formparams.add(new BasicNameValuePair("phone", model.getPhone()));
        formparams.add(new BasicNameValuePair("bankCode", model.getBankCode()));
        formparams.add(new BasicNameValuePair("MD5Info", MD5Info));
        formparams.add(new BasicNameValuePair("payType", "KJPAY"));//固定：RZPAY（认证支付）
        formparams.add(new BasicNameValuePair("cardType", "D"));
        formparams.add(new BasicNameValuePair("month", ""));
        formparams.add(new BasicNameValuePair("year", ""));
        formparams.add(new BasicNameValuePair("CVV2", ""));
        formparams.add(new BasicNameValuePair("transDate", transDate));
        formparams.add(new BasicNameValuePair("transTime", transTime));
        formparams.add(new BasicNameValuePair("payAmount", model.getAmount()));
        return formparams;
    }

    /**
     * 组建请求参数-快捷支付接口
     * @param model
     * @param notifyUrl
     * @param mercNo
     * @param md5key @return
     * @param web_url
     */
    public static List<NameValuePair> buildQuickNameParams(PayModel model, String notifyUrl, String mercNo, String md5key, String web_url) throws Exception{

        String MD5Info;                    // MD5 加密字符串
        MD5 md5 = new MD5();
        String apiUrl = web_url;
        String NotifyURL = apiUrl + notifyUrl;

        String[] md5ReqMap = new String[]{"merNo", "merOrderNo", "custName", "phone", "cardNo", "idType",
                "idNo", "payAmount", "bankCode", "NotifyURL"};

        Map<String, String> mapStr = new LinkedHashMap<>();

        model.setBankCode(model.getBankCode());
        String[] value = new String[]{mercNo, model.getMerOrderNo(), model.getAccountName(), model.getPhone(), model.getBankNo(), EPayConsts.ID_TYPE_0, model.getIdCardNo()
                , model.getAmount(), model.getBankCode(), NotifyURL};
        for (int i = 0; i < md5ReqMap.length; i++) {
            mapStr.put(md5ReqMap[i], value[i]);
        }

        String strBeforeMd5 = joinMapValue(mapStr, '&') + md5.getMD5Info(md5key).toUpperCase();

        System.out.println(strBeforeMd5);

        MD5Info = md5.getMD5Info(strBeforeMd5).toUpperCase();

        System.out.println(MD5Info);

        // 创建参数队列
        List<NameValuePair> formparams = new ArrayList<>();

        formparams.add(new BasicNameValuePair("merNo", mercNo));
        formparams.add(new BasicNameValuePair("merOrderNo", model.getMerOrderNo()));
        formparams.add(new BasicNameValuePair("cardNo", model.getBankNo()));
        formparams.add(new BasicNameValuePair("custName", model.getAccountName()));
        formparams.add(new BasicNameValuePair("idType", EPayConsts.ID_TYPE_0));
        formparams.add(new BasicNameValuePair("idNo", model.getIdCardNo()));
        formparams.add(new BasicNameValuePair("phone", model.getPhone()));
        formparams.add(new BasicNameValuePair("purpose", model.getPhone() + "快捷支付" + model.getAmount() + "元")); //交易信息
        formparams.add(new BasicNameValuePair("payAmount", model.getAmount())); //交易信息
        formparams.add(new BasicNameValuePair("bankCode",model.getBankCode()));
        formparams.add(new BasicNameValuePair("payType", "KJPAY"));//固定：RZPAY（认证支付）
        formparams.add(new BasicNameValuePair("NotifyURL", NotifyURL)); //异步通知地址
        formparams.add(new BasicNameValuePair("txnTime", model.getTxnTime()));
        formparams.add(new BasicNameValuePair("smsCode", model.getSmsCode()));
        formparams.add(new BasicNameValuePair("MD5Info", MD5Info));

        return  formparams;
    }

    /**
     * 快捷支付-接口版(改造)
     * @param formparams
     * @return
     */
    public static WithHoldingResp hfDaiKouTrade(List<NameValuePair> formparams) {

        // 创建默认的httpClient实例.
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost("https://fastpay.95epay.cn/pay/hfDaikouTrade.action");

        UrlEncodedFormEntity uefEntity;
        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            System.out.println("executing request " + httppost.getURI());
            try (CloseableHttpResponse response = httpclient.execute(httppost)) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String responseStr = EntityUtils.toString(entity, "UTF-8");
                    System.out.println("Response content: " + responseStr);
                    if (!StringUtils.isBlank(responseStr)) {
                        return JSON.parseObject(responseStr, WithHoldingResp.class);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
